const mongoose = require('mongoose');
const COLLECTIONS = require('./collections');

// 支付状态枚举
const PAYMENT_STATUS = {
  PENDING: 'pending',      // 待支付
  SUCCESS: 'success',      // 支付成功
  FAILED: 'failed',        // 支付失败
  CANCELLED: 'cancelled',  // 已取消
  REFUNDED: 'refunded',    // 已退款
  EXPIRED: 'expired'       // 已过期
};

// 支付方式枚举
const PAYMENT_METHOD = {
  ALIPAY: 'alipay',        // 支付宝
  WECHAT: 'wechat',        // 微信支付
  UNIONPAY: 'unionpay',    // 银联支付
  BALANCE: 'balance',      // 余额支付
  COD: 'cod'               // 货到付款
};

// 支付记录模式
const PaymentSchema = new mongoose.Schema(
  {
    // 支付订单号（系统生成）
    paymentNo: {
      type: String,
      required: true,
      unique: true,
      index: true
    },
    
    // 关联的订单ID
    orderId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Order',
      required: true,
      index: true
    },
    
    // 用户ID
    userId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User',
      required: true,
      index: true
    },
    
    // 支付方式
    paymentMethod: {
      type: String,
      required: true,
      enum: Object.values(PAYMENT_METHOD)
    },
    
    // 支付金额（分为单位）
    amount: {
      type: Number,
      required: true,
      min: 0
    },
    
    // 支付状态
    status: {
      type: String,
      required: true,
      enum: Object.values(PAYMENT_STATUS),
      default: PAYMENT_STATUS.PENDING,
      index: true
    },
    
    // 第三方支付平台的交易号
    thirdPartyTransactionId: {
      type: String,
      index: true
    },
    
    // 第三方支付平台返回的原始数据
    thirdPartyResponse: {
      type: mongoose.Schema.Types.Mixed
    },
    
    // 支付URL（用于跳转支付）
    paymentUrl: {
      type: String
    },
    
    // 二维码数据（用于扫码支付）
    qrCode: {
      type: String
    },
    
    // 支付过期时间
    expiresAt: {
      type: Date,
      required: true,
      index: true
    },
    
    // 支付完成时间
    paidAt: {
      type: Date
    },
    
    // 退款金额（分为单位）
    refundAmount: {
      type: Number,
      default: 0,
      min: 0
    },
    
    // 退款时间
    refundedAt: {
      type: Date
    },
    
    // 退款原因
    refundReason: {
      type: String
    },
    
    // 支付失败原因
    failureReason: {
      type: String
    },
    
    // 回调通知次数
    notifyCount: {
      type: Number,
      default: 0
    },
    
    // 最后一次回调时间
    lastNotifyAt: {
      type: Date
    },
    
    // 备注信息
    note: {
      type: String
    }
  },
  {
    timestamps: true,
    collection: COLLECTIONS.PAYMENTS
  }
);

// 索引
PaymentSchema.index({ orderId: 1, status: 1 });
PaymentSchema.index({ userId: 1, createdAt: -1 });
PaymentSchema.index({ paymentMethod: 1, status: 1 });
PaymentSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 }); // TTL索引，自动删除过期记录

// 生成支付订单号
PaymentSchema.statics.generatePaymentNo = function() {
  const timestamp = Date.now().toString();
  const random = Math.random().toString(36).substring(2, 8).toUpperCase();
  return `PAY${timestamp}${random}`;
};

// 检查支付是否过期
PaymentSchema.methods.isExpired = function() {
  return new Date() > this.expiresAt;
};

// 检查是否可以退款
PaymentSchema.methods.canRefund = function() {
  return this.status === PAYMENT_STATUS.SUCCESS && 
         this.refundAmount < this.amount;
};

// 获取剩余可退款金额
PaymentSchema.methods.getRefundableAmount = function() {
  if (!this.canRefund()) return 0;
  return this.amount - this.refundAmount;
};

// 更新支付状态
PaymentSchema.methods.updateStatus = function(status, additionalData = {}) {
  this.status = status;
  
  if (status === PAYMENT_STATUS.SUCCESS) {
    this.paidAt = new Date();
  } else if (status === PAYMENT_STATUS.FAILED) {
    this.failureReason = additionalData.failureReason;
  } else if (status === PAYMENT_STATUS.REFUNDED) {
    this.refundedAt = new Date();
    this.refundReason = additionalData.refundReason;
    if (additionalData.refundAmount) {
      this.refundAmount += additionalData.refundAmount;
    }
  }
  
  // 更新第三方响应数据
  if (additionalData.thirdPartyResponse) {
    this.thirdPartyResponse = additionalData.thirdPartyResponse;
  }
  
  // 更新第三方交易号
  if (additionalData.thirdPartyTransactionId) {
    this.thirdPartyTransactionId = additionalData.thirdPartyTransactionId;
  }
  
  return this.save();
};

// 记录回调通知
PaymentSchema.methods.recordNotify = function() {
  this.notifyCount += 1;
  this.lastNotifyAt = new Date();
  return this.save();
};

const Payment = mongoose.model('Payment', PaymentSchema);

module.exports = {
  Payment,
  PAYMENT_STATUS,
  PAYMENT_METHOD
};
